<template>
<div>
      <FouDialog
      :title="'添加/修改'"
      :width="'60%'"
      v-model:dialogValue="dialogValue"
    >
    <template #content>
            <el-form :model="form" label-width="120px" :rules="rules" ref="ruleFormRef">
      <el-row :gutter="24" >
        <el-col :span="8">
          <el-form-item label="套票名稱" prop="name"><el-input v-model="form.name" /></el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="使用期限" prop="deadline"><el-input v-model="form.deadline" > <template #append>/天數</template></el-input></el-form-item>
        </el-col> -->
        <el-col :span="8" >
          <el-form-item label="適用課程" prop="course_id">
              <el-select :data-class="className" :popper-class="className" v-selectLoadMore="handleScroll" v-model="form.course_id"  size="default" style="width:100%" :loading="serloading" multiple filterable remote reserve-keyword remote-show-suffix :remote-method="remoteMethod">
                <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24" >
          <el-col :span="5" >
            <el-form-item label="套票規格" prop="ticket_item">
              <el-button  class="button"  :color="addButtonType ? '#F72C25' : '#50BC58' " :icon="addButtonType ? 'CircleClose' :'ZoomIn' " @click="addTicket" >{{addButtonType ? '取消' : '添加'}}</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="19" >
            <specifications v-show="addButtonType" @addticket="specClick" :showTicket="showTicket" :showTicketIndex='showTicketIndex'></specifications>
          </el-col>
          <el-col :span="24">
                          <ProTable
                :data="form.ticket_item"
                :column="ticketcolumn"
                :elProps="elProps"
                :page="{}"
                :rowControl="[]"
                :disabled="[]"
                :controlWidth="[]"
              >
                    <template #search_operate>
                        <el-table-column   min-width="200px" label="操作" >
                          <template #default="scope">
                                <el-link @click="lookSpeci(scope.$index, scope.row)"  type='primary' :underline="false">查看</el-link >
                              <el-popconfirm 
                                  confirm-button-text="確認"
                                  cancel-button-text="NO"
                                  title="確認刪除該數據?"
                                   @confirm="confirmEvent"
                                >
                                  <template #reference>
                                <el-link style="margin-left:20px" @click="deleteSpeci(scope.$index, scope.row)" type='primary' :underline="false">刪除</el-link >
                                </template>
                              </el-popconfirm>
                          </template>
                        </el-table-column>
                  </template>
              </ProTable>
          </el-col>
      </el-row>

    </el-form>
    </template>
      <template #footer>
                       <div class="flex justify-end mt-10 w-[100%]" >
            <el-button @click="dialogValue = false">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef,buttonType)" color="#081F42"
              >確定</el-button
            >
           </div>
      </template>
      </FouDialog>

</div>
</template>

<script setup>
import { ref  ,reactive, watch } from 'vue' 
import {message,messageBox,loading,closeLoading} from '@/common/function.js'
import specifications from './specifications.vue'
import {elProps} from './index'
import {addTickets,updateTickets,course} from "@/http/index.js";
const className = 'lazyselect'
const specClick = (value,index)=>{
  console.log(value,index);
  if (!index) {
  form.ticket_item.push(value)
  }else{
  form.ticket_item[index-1]= value
      showTicketIndex.value = ''
  }
}
const showTicket = ref({})
const showTicketIndex = ref('')
const lookSpeci = (index,row)=>{
    addButtonType.value = true
    showTicketIndex.value = index +1
    showTicket.value = row
}
const speciIndex = ref('')
const deleteSpeci = (index,row)=>{
  speciIndex.value = index
}
const confirmEvent = ()=>{
      form.ticket_item.splice(speciIndex.value, 1)
}

const addButtonType = ref(false)
const dialogValue = ref(false)
const form = reactive({
    name: "",
    // deadline: "",
    course_id: "",
    ticket_item: [],
});
const  rules = reactive({
        name:{required:true,message:'请输入套票名稱',trigger: ['blur', 'change']},
        // deadline:{required:true,message:'请输入套票使用期限',trigger: ['blur', 'change']},
        course_id:{required:true,message:'请输入適用課程',trigger: ['blur', 'change']},
        ticket_item:{required:true,message:'请添加套票規格',trigger: ['blur', 'change']},
    })
const ticketcolumn = reactive({
  num:'數量',
  price:'價格',
  deadline:'使用期限(天)'
})
const ruleFormRef = ref('')
const buttonType = ref('')

const addTicket = ()=>{
  addButtonType.value = !addButtonType.value
  console.log(addButtonType.value);
}

const confirm = (formEl,type)=>{
  if (!formEl) return;
      formEl.validate(async (e)=>{
        if (e) {
          let FormData = JSON.parse(JSON.stringify(form))
        FormData.ticket_item = JSON.stringify(FormData.ticket_item)
        FormData.course_id = FormData.course_id.toString()
          if (type == 'add') {
            delete FormData.id
            await addTableList(FormData)
          }
          if (type == 'edit') {
            await updateTableList(FormData)
          }
        }
    })
}

const addTableList = async(e)=>{
  const data = await addTickets(e)
  console.log(data);
  if (data.code == 200) {
    dialogValue.value = false
   await emit('addConfirm')
    message('添加套票成功')
  }
}
// // 修改產品
const updateTableList = async (e) => {
  const data = await updateTickets(e);
  if (data.code == 200) {
        dialogValue.value = false
    await emit('addConfirm')
    message('修改套票規格成功')
  }
};

const props = defineProps({
    echo:Object,
    courseList:Object
})
Object.assign(form,props.echo)
watch(()=>props.echo,(newval)=>{
Object.assign(form,newval)

})
const options = ref([])
options.value = props.courseList
watch(()=>props.courseList,(newval)=>{
  options.value = newval
})

const obj = reactive({
  page: 1,
  limit: 10,
  name: "",
  status: "",
  time: "",
  school_id:localStorage.getItem('school_id')
});
const serloading = ref(false)
// select搜索
const remoteMethod = async(query)=>{
  tatal.value = true
  obj.page = 1
  if (query) {
    serloading.value = true
    setTimeout(async() => {
      serloading.value = false
    const data = await course({name:query})
    if (data.code == 200) {
      options.value = data.data.data
    }
    }, 200)
  }else{
    serloading.value = true
    setTimeout(async() => {
      serloading.value = false
    const data = await course({name:''})
    if (data.code == 200) {
      options.value = data.data.data
    }
    }, 200)
  }
}
// select翻页
const tatal = ref(true)
const  handleScroll = async()=>{
  if (!tatal.value)return
  obj.page +=1
  const data = await course(obj)
    if (data.code == 200) {
      options.value = [...options.value,...data.data.data]
      if (data.data.current_page == data.data.last_page) {
        message('當前已是最後一頁','warning')
        tatal.value = false
      }
    }
    console.log(options.value);
    
}
const emit = defineEmits(['addConfirm','addCancal'])
defineExpose({
    dialogValue,buttonType
})
</script>

<style lang='less'  scoped>
.button{
  color: #fff;
}

</style>